function [tier1, tier2 tier3, sep2, sep3, order] = multiTierLabel(tier1, tier2, tier3)

% multitierlabel generates an ordered list of label entries for multi tiered or nested labels. 
% Usage [tier1, tier2 tier3, sep2, sep3, order] = multiTierLabel(tier1, tier2, tier3)
% where tier1, tier2 and tier3 input parameters contain the label entry values 
% for each level of labels, for each data point. 
% The output tier1, tier2, tier3 are the ordered list of the three levels of labels.
% The sep2 and sep3 are the grid positions of separators for level2 and level3 entries.
% See chapter 2, Boxplots with multitiered labeling for more explanation.

tier1Original = tier1;

[tier3 I] = sort(tier3);
tier2 = tier2(I);
tier1 = tier1(I);
tier3uniqueLabels = unique(tier3);
for i = 1:length(tier3uniqueLabels)
    H = find(cellfun('length',strfind(tier3,tier3uniqueLabels{i})));
    [tier2(H) I] = sort(tier2(H));
    tier1(H) = tier1(H(I));
end

%[tier1; tier2; tier3]' %Verify the orde
sep2 = []; sep3 = [];
for i = 1:length(tier2)-1
    if ~strcmp(tier2(i),tier2(i+1))
        sep2 = [sep2 i;];
    end
    if ~strcmp(tier3(i),tier3(i+1))
        sep3 = [sep3 i;];
    end
end

%determine the re-ordering
for i = 1:length(tier1)
    order(i) = find(cellfun('length',strfind(tier1Original,tier1{i})));
end